package com.caifu.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.caifu.bean.Result;
import com.caifu.pojo.SysLog;
import com.caifu.pojo.SysLoginError;
import com.caifu.pojo.SysUser;
import com.caifu.service.SysLogService;
import com.caifu.service.SysLoginErrorService;
import com.caifu.service.SysUserService;
import com.caifu.util.ShiroUtil;
import com.caifu.util.Util;
import com.caifu.vo.MenuVo;
import net.sf.json.JSONObject;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import springfox.documentation.annotations.ApiIgnore;

import java.util.Date;
import java.util.List;

/**
 * @Auther: Lyf
 * @Date: 2020/7/3 19:57
 * @Description:
 */
@Controller
@ApiIgnore
public class LoginController extends AbstractController {

    final static Logger logger = LoggerFactory.getLogger(LoginController.class);

    /* @Autowired
     private SysMenuService menuService;*/
    @Autowired
    private SysUserService userService;
    @Autowired
    private SysLogService logService;
    @Autowired
    private SysLoginErrorService errorService;


    @GetMapping(value = {"", "/", "/login", "login"})
    public String login(ModelMap model, Integer type) {
        if (type == null) {
            type = 0;
        }
        model.put("type", type);
        return "view/sys/login";
    }

    @PostMapping("/login")
    @ResponseBody
    public JSONObject authentication(SysUser user) throws Exception {
        SysUser oldUser = new SysUser();
        JSONObject obj = new JSONObject();
        int code = 200;
        String msg = "登陆成功！";
        Subject subject = SecurityUtils.getSubject();
        try {
            //判断当日连续失败登陆次数是否超过5次
            int count = errorService.count(new QueryWrapper<SysLoginError>().eq("day", Util.currentDate()).eq("login_name", user.getUserId()));
            if (count >= 5) {
                msg = "连续登陆失败次数超过5次, 账户已锁";
                code = 103;
            } else {
                oldUser = userService.getUserByLoginName(user.getUserId());
                if (oldUser == null) {
                    int closeCount = userService.count(new QueryWrapper<SysUser>().eq("user_id", user.getUserId()).ne("status", "1"));
                    if (closeCount > 0) {
                        msg = "账户已停用, 无法登陆";
                        code = 104;
                    } else {
                        msg = "账户不存在";
                        code = 104;
                    }
                } else {
                    if (!subject.isAuthenticated()) {
                        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(
                                user.getUserId(),
                                user.getUserPwd()
                        );
                        subject.login(usernamePasswordToken);
                        //subject.getSession().setTimeout(43200000);//12个小时
                        subject.getSession().setTimeout(1800000);
                        subject.getSession().setAttribute("user", user);
                        userService.updateLoginTime(user.getUserId());
                        userService.loginSuccess(oldUser.getId(), user.getUserId());
                    }
                    /*UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(
                            user.getUserId(),
                            user.getUserPwd()
                    );
                    subject.login(usernamePasswordToken);
                    //subject.getSession().setTimeout(43200000);//12个小时
                    subject.getSession().setTimeout(1800000);
                    subject.getSession().setAttribute("user", user);
                    userService.updateLoginTime(user.getUserId());
                    userService.loginSuccess(oldUser.getId(), user.getUserId());*/
                    SysUser user1 = getUser();
                    String pwd = ShiroUtil.sha256("123456", user1.getSalt());
                    if (pwd.equals(user1.getUserPwd()) && !("0".equals(user1.getUserType()))) {
                        obj.put("code", "2020");
                        return obj;
                    }
                }
            }
        } catch (AuthenticationException e) {
            code = 101;
            msg = "账号或密码错误！";
            if (oldUser != null) {
                userService.loginError(oldUser.getId(), oldUser.getUserId());
            }
        } catch (AuthorizationException e) {
            msg = "没有权限";
            code = 102;
        } catch (Exception e) {
            e.printStackTrace();
        }
        obj.put("code", code);
        obj.put("msg", msg);
        return obj;
    }

    @RequestMapping("/index")
    public String index(ModelMap model) throws Exception {
        SysUser user = getUser();
        //当前用户
        SysUser tmpUser = userService.getById(getUserNo());
        //用户菜单
        List<MenuVo> userMenu = userService.getUserMenuById(getUserNo());
        if (tmpUser == null) {
            throw new Exception("SysUser查询失败，userNo=" + getUserNo());
        }
        model.put("userName", user.getUserId());
        model.put("menus", userMenu);
        return "view/sys/index";
    }

    @RequestMapping("/welcome")
    public String welcome() {
        return "view/sys/welcome";
    }

    @GetMapping("updatePwd")
    public String updatePwd() {
        return "view/sys/update_pwd";
    }

    @RequestMapping("/getMenuByUser")
    @ResponseBody
    public Result getMenuByUser() throws Exception {
     /*   try {
            Object obj = menuService.getMenuByUser(getUser().getId());
            return ResultUtil.success("data", obj);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("获取用单失败！");
            throw new Exception("获取用单失败！");
        }*/
        return null;
    }

    //退出登录
    @RequestMapping("/outLogin")
    public String outLogin() {
        try {
            ShiroUtil.logout();
            return "redirect:login";
        } catch (Exception e) {
            e.printStackTrace();
            //日志记录  sys 组织架构模块  sys-206 操作员退出
            return "";
        }
    }
}
